/**
 * oss上传
 */

import { server_request } from "../../utils/request";
import { session_storage } from "../../utils/storage";
import uploadConfig from "../../config/upload";
import OSS from "ali-oss";


function ossUpload( file, config){
    let oss_config = uploadConfig.oss.upload_config;
    // console.log( getSts());
    // getSts()
    session_storage( "oss_sts", {
        ajax_url: uploadConfig.oss.get_sts_token_url,
        errorMsg: "获取OSS临时凭证失败",
        value: config.sts,
    })
        .then( (sts) => {

            if( sts != null){
                oss_config.accessKeyId = sts.credentials.AccessKeyId;
                oss_config.accessKeySecret = sts.credentials.AccessKeySecret;
                oss_config.stsToken = sts.credentials.SecurityToken;
            }

            toUpload( file, oss_config, config);
        })
        .catch( (msg, res) => {
            config.failure && config.failure( { code: 500, msg: msg, data: res});
        });
}

function toUpload( file, oss_config, config){

    let client = new OSS( oss_config);
    try{
        let fileOnlinePath = config.fileOnlinePath;

        let success_url = ( [
            "http",
            ( oss_config.secure ? "s" : ""),
            "://",
            oss_config.bucket,
            ".",
            oss_config.endpoint,
            fileOnlinePath
        ]).join( "");

        let result = client.multipartUpload( fileOnlinePath, file, {
            progress: function (p, checkpoint, res) {
                config.progress && config.progress( { percent: Math.floor(p * 100)});
            }
        });
        result.then( ( res) => {
            config.success && config.success( {
                code: 200,
                msg: "success",
                data: success_url
            });
        });
    }catch( e){
        config.failure && config.failure( { code: 500, msg: "上传失败", data: e});
        client.cancel();
        console.error( e);
    }
}


export default function uploadFile( file, config) {
    ossUpload( file, config);
}